class Rbac
  class << self
    # TODO:获取全部backend的权限
    def backend_permissions
      return ""
    end

    def convert_ability_data(ctl, action, role)
      reversed_abilities = Rails.cache.fetch("auto_abilities_#{role.id}")
      unless reversed_abilities.present?
        update_ability_data(role)
        reversed_abilities = Rails.cache.fetch("auto_abilities_#{role.id}")
      end
      return false unless reversed_abilities.present?
      return false unless reversed_abilities[ctl].present?
      reversed_abilities[ctl].detect {|a| a == action}.present?
    end

    def update_ability_data(role)
      Rails.cache.write("auto_abilities_#{role.id}", reverse_ability_data(role.ability_data))
    end
  end

  private

  def self.reverse_ability_data(raw_data)
    reversed_data = {}
    resources = []
    access_abilities = abilities_data
    return reversed_data if raw_data.blank?
    raw_data.each do |ability, permissions|
      permissions.each do |permission|
        resources.push(access_abilities[ability]['permissions'].map {|key, items| items['resources'] if key == permission})
      end
    end

    resources.flatten.compact.each do |resource|
      resource.each do |ctl, actions|
        all_actions = []
        actions.each {|action| all_actions.push(action)}
        reversed_data[ctl] = reversed_data[ctl].to_a.push(all_actions.uniq).flatten
      end
    end
    return reversed_data
  end



end
